import { objectType, extendType, stringArg } from "@nexus/schema";
import { getUserId } from "../utils";

export const User = objectType({
  name: "User",
  definition(t) {
    t.string("id");
    t.string("name");
    t.string("password");
    t.field("projects", { nullable: true, type: "Project", list: true });
  },
});

export const UserQuery = extendType({
  type: "Query",
  definition(t) {
    t.field("user", {
      type: "User",
      args: {
        name: stringArg({ required: true }),
      },
      resolve(__root, args, ctx) {
        return ctx.db.user.findOne({
          where: { name: args.name },
          include: {
            projects: true,
          },
        });
      },
    });
  },
});

export const UsersQuery = extendType({
  type: "Query",
  definition(t) {
    t.field("users", {
      type: "User",
      list: true,
      resolve(__root, args, ctx) {
        return ctx.db.user.findMany({
          include: {
            projects: true,
          },
        });
      },
    });
  },
});

export const UserProjectsQuery = extendType({
  type: "Query",
  definition(t) {
    t.field("userProjects", {
      type: "User",
      resolve(__root, args, ctx) {
        console.log("user id:", ctx.userId);
        return ctx.db.user.findOne({
          where: { id: ctx.userId },
          include: {
            projects: true,
          },
        });
      },
    });
  },
});

export const CreateUserMutation = extendType({
  type: "Mutation",
  definition(t) {
    t.field("createUser", {
      type: "User",
      args: {
        name: stringArg({ required: true }),
        password: stringArg({ required: true }),
      },
      resolve(_root, args, ctx) {
        const userId = getUserId(ctx.token);
        if (!userId) {
          throw new Error("Invalid userId");
        }
        const user = {
          name: args.name,
          password: args.password,
        };
        return ctx.db.user.create({ data: user });
      },
    });
  },
});

export const DeleteUserMutation = extendType({
  type: "Mutation",
  definition(t) {
    t.field("deleteUser", {
      type: "User",
      args: {
        name: stringArg({ required: true }),
      },
      resolve(_root, args, ctx) {
        const userId = getUserId(ctx.token);
        if (!userId) {
          throw new Error("Invalid userId");
        }
        return ctx.db.user.delete({
          where: { name: args.name },
        });
      },
    });
  },
});
